import WS from '@/libs/ws.js'
import { reactive } from 'vue'
import axios from 'axios'

export const scrollContainer = ref(null)
export const messageObj = {}

export const state = reactive({
  messages: [],
  messageId: null,
  messageIndex: 0,
  dialog: {
    input: { show: false },
  },
})

class Chat {
  constructor() {
    this.init()
  }

  init() {
    const ws = new WS({
      url: 'ws://10.254.32.20:8765',
      onMessage: value => {
        if (value.indexOf('input_paramter') != -1) {
          state.dialog.input.show = true
        } else {
          onMessage(value)
        }
      },
    })

    this.ws = ws
  }

  send(data) {
    this.ws.send(data)
  }

  input(data) {
    state.messages.push({
      role: 'user',
      type: 'text',
      content: data,
    })

    this.send('input: ' + data)
    scrollToBottom()
  }

  inputParamter(data) {
    state.messages.push({
      role: 'user',
      type: 'text',
      content: data,
    })

    this.send('input_paramter: ' + data)
    scrollToBottom()
  }
}

export const chat = new Chat()

function onMessage(item) {
  const { type, data } = parseOnChainEnd(item)

  const { run_id, parent_run_id } = data || {}

  const result = {
    level: 0,
    status: 0,
    childrens: [],
    expand: true,
    role: 'system',
    input: null,
    output: [],

    type,
    run_id,
  }

  if (run_id) {
    if (!messageObj[run_id]) messageObj[run_id] = result
    state.messageId = run_id

    // 完成
    if (type.indexOf('_end') != -1) {
      messageObj[run_id].output = item
      messageObj[run_id].status = 1
    } else {
      messageObj[run_id].type = type
      messageObj[run_id].input = item
    }
  }

  if (parent_run_id != 'None' && parent_run_id) {
    const parent = messageObj[parent_run_id]
    if (parent) {
      result.level = parent.level + 1
      parent.childrens.push(result)
    } else {
      state.messages.push(result)
    }
  } else {
    state.messages.push(result)
  }

  state.messageIndex++

  scrollToBottom()
}

function scrollToBottom() {
  if (scrollContainer.value) {
    setTimeout(() => {
      scrollContainer.value.scrollTo({
        top: scrollContainer.value.scrollHeight,
        behavior: 'smooth',
      })
    })
  }
}

function parseOnChainEnd(input) {
  // 提取 type
  const type = input.split(':')[0].trim()

  // 提取 msg 部分
  const msgStart = input.indexOf('msg:{')
  const msgEnd = input.indexOf(' kwargs:', msgStart) + 1
  const msgStr = input.slice(msgStart + 4, msgEnd).trim()
  let data
  try {
    data = JSON.parse(msgStr)
  } catch (e) {
    console.error('JSON解析失败', input)
  }

  // 提取 kwargs 部分
  const kwargsStart = input.indexOf('kwargs:{')
  const kwargsEnd = input.lastIndexOf('}') + 1
  const kwargsStr = input.slice(kwargsStart, kwargsEnd).trim()

  // 构建 content
  const content = kwargsStr

  return { type, data, content }
}

axios({
  url: 'http://127.0.0.1:1200/api/message',
}).then(res => {
  res.data.data.forEach((item, index) => {
    setTimeout(() => {
      onMessage(item)
    }, index * 1)
  })
})
